#include "node.hh"
#include <QDir>
#include <stdio.h>

dsa::Node::Node(dsa::Node::Type type)
	: QObject()
	, _parent (0)
	, _size (0)
	, _numDirs (0)
	, _numFiles (0)
	, _name ("")
	, _type (type)
  , _hover (false)
{
}

dsa::Node::~Node()
{
	_parent = 0;
	foreach (Node *node, _children)
		{
			delete node;
		}
	_children.clear();
}


QString dsa::Node::TypeString(dsa::Node::Type type)
{
	switch (type)
		{
		case dsa::Node::Type_Dir:
			return "Dir";
		case dsa::Node::Type_File:
			return "File";
		}
	return "Undefined";
}

dsa::Node::Type dsa::Node::GetType() const
{
	return _type;
}

void dsa::Node::SetName(const QString &name)
{
	_name = name;
}

const QString& dsa::Node::GetName () const
{
	return _name;
}

void dsa::Node::SetSize(qint64 size)
{
	_size = size;
}

qint64 dsa::Node::GetSize() const
{
	return _size;
}

QString dsa::Node::GetSizeString(qint64 size)
{
	unsigned num = 0;

	double ds = size;
	while (ds > 900.0)
		{
			ds /= 1024.0;
			num ++;
		}

	QString name;
	name.sprintf("%.2f", ds);

	switch (num)
		{
		case 0:
			name += "B";
			break;
		case 1:
			name += "KB";
			break;
		case 2:
			name += "MB";
			break;
		case 3:
			name += "GB";
			break;
		case 4:
			name += "TB";
			break;
		}
	return name;
}

QString dsa::Node::GetFullName() const
{
	QString name;
	if (_parent)
		{
			name = _parent->GetFullName() + QDir::separator();
		}
	name += _name;
	return name;
}

void dsa::Node::AddNode(Node *node)
{
	_children.push_back(node);
	node->_parent = this;
}

void dsa::Node::RemoveNode(Node *node)
{
	if (_children.removeAll(node) > 0)
		{
			node->_parent = 0;
		}
}


void dsa::Node::EvalData()
{
	_size = 0;

	_numDirs = 0;
	_numFiles = 0;

	foreach (dsa::Node* node, _children)
		{
			_size += node->GetSize();

			_numDirs += node->GetNumberOfDirs();
			_numFiles += node->GetNumberOfFiles();
		}

	switch (_type)
		{
		case Type_Dir:
			_numDirs++;
			break;

		case Type_File:
			_numFiles++;
			break;
		}

}

void dsa::Node::Debug(int indent)
{
	for (int i=0; i<indent; ++i)
		{
      printf ("    ");
		}
	printf ("%s : %s : %d : %s   Num (Files: %llu  Dirs: %llu)\n",
					(const char*)dsa::Node::TypeString(_type).toAscii(),
					(const char*)_name.toAscii(),
					_children.size(),
					(const char*)GetSizeString(_size).toAscii(),
					_numFiles,
					_numDirs);
	fflush(stdout);
	foreach (dsa::Node *child, _children)
		{
      child->Debug(indent+1);
		}
}

bool dsa::Node::IsHover() const
{
  return _hover;
}

void dsa::Node::ChangeHover(bool hover)
{
  _hover = hover;
  emit HoverChanged(hover);
}


dsa::DirNode::DirNode()
	: dsa::Node(dsa::Node::Type_Dir)
{

}

dsa::FileNode::FileNode()
	: dsa::Node(dsa::Node::Type_File)
{

}


dsa::DummyNode::DummyNode ()
  : dsa::Node(dsa::Node::Type_Dummy)
{

}
